package com.yiyuan.app.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AppleVerifyUtils {
    /**
     * 苹果内购沙盒环境
     */
    private static final String url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
    /**
     * 苹果内购正式环境
     */
    private static final String url_verify = "https://buy.itunes.apple.com/verifyReceipt";
    /**
     * 秘钥 （自动订阅服务需要秘钥）
     */
    private static final String KEY = "e731a5cd185048e996f4671a45959539";


    /**
     * 苹果服务器内购验证票据
     *
     * @param receipt 验证收据
     * @param type    环境  （1 生产；0 开发）
     * @return
     */
    public static String verifyApple(String receipt, int type) {
        String url;
        //环境判断 线上/开发环境用不同的请求链接
        if (type == 0) {
            url = url_sandbox;
        } else {
            url = url_verify;
        }

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(url);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("receipt-data", receipt);
            jsonObject.put("password", KEY);

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody stringBody = RequestBody.create(mediaType, jsonObject.toString());
            Request request = new Request
                    .Builder()
                    .url(console)
                    .post(stringBody)
                    .build();

            return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
        } catch (Exception e) {
            log.error("[ios verify error]");
            return null;
        }
    }

    private static class TrustAnyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }
}
